package com.cy.myblog.action.article;

import com.alibaba.fastjson.JSON;
import com.cy.myblog.action.BaseAction;
import com.cy.myblog.model.Tclassify;
import com.cy.myblog.pageModel.Json;
import com.cy.myblog.service.ClassifyServiceI;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by Administrator on 2015/7/12.
 */
@Controller("classifyAction")
@Scope("prototype")
public class ClassifyAction extends BaseAction{

    private ClassifyServiceI classifyService;

    private List<Tclassify> allClassify;
    private String newClassify;
    private Json json = null;

    public Json getJson() {
        return json;
    }

    public void setJson(Json json) {
        this.json = json;
    }

    public String getNewClassify() {
        return newClassify;
    }

    public void setNewClassify(String newClassify) {
        this.newClassify = newClassify;
    }

    public List<Tclassify> getAllClassify() {
        return allClassify;
    }

    public void setAllClassify(List<Tclassify> allClassify) {
        this.allClassify = allClassify;
    }

    @Resource(name = "classifySerivce")
    public void setClassifyService(ClassifyServiceI classifyService) {
        this.classifyService = classifyService;
    }

    public String queryAll(){
        allClassify = classifyService.findAll();
        return TOJSON;
    }

    public String update(){
        json = new Json();
        List<Tclassify> newData = JSON.parseArray(newClassify,Tclassify.class);
        List<Tclassify> oldData = classifyService.findAll();

        /* 对数据排序以便于使用binarySearch二分法查找 */
        Collections.sort(newData,new Comparator<Tclassify>(){
            public int compare(Tclassify b1, Tclassify b2) {
                return String.valueOf(b1.getId()).compareTo(String.valueOf(b2.getId()));
            }
        });

        Collections.sort(oldData,new Comparator<Tclassify>(){
            public int compare(Tclassify b1, Tclassify b2) {
                return String.valueOf(b1.getId()).compareTo(String.valueOf(b2.getId()));
            }
        });

        try {
            for(Tclassify data : oldData){
                int index = Collections.binarySearch(newData,data,new Comparator<Tclassify>(){
                    public int compare(Tclassify b1, Tclassify b2) {
                        return String.valueOf(b1.getId()).compareTo(String.valueOf(b2.getId()));
                    }
                });

                if(index < 0){
                    classifyService.delete(data);
                }
            }

            for(Tclassify data : newData){
                classifyService.update(data);
            }
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg("操作失败,网络繁忙");
        }

        return TOJSON;
    }
}
